package yiran.stock.gui;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import yiran.stock.Stock;
import yiran.stock.lang.LangHelper;
import yiran.stock.StockManager;

import java.util.*;

public class StockGUI {
    private final StockManager stockManager;
    public final Player player;
    private final Inventory inventory;
    private int currentPage = 0;
    private static int itemsPerPage = 28;
    private final List<String> currentPageSymbols = new ArrayList<>();
    private final Stock plugin;

    public StockGUI(Player player, StockManager stockManager, Stock plugin) {
        this.player = player;
        this.stockManager = stockManager;
        this.plugin = plugin;
        this.inventory = Bukkit.createInventory(
                player,
                54,
                LangHelper.getString("gui.title") + " - " + LangHelper.getString("stocks.list-title-short")
        );

    }

    public static void setItemsPerPage(int count) {
        itemsPerPage = count;
    }

    public void open() {
        updatePage(0);
        player.openInventory(inventory);
    }

    private void updatePage(int page) {
        currentPage = page;
        inventory.clear();

        Map<String, Double> prices = stockManager.getStockPrices();
        List<String> symbols = new ArrayList<>();
        for (Map.Entry<String, Double> entry : prices.entrySet()) {
            if (entry.getValue() > 0) {
                symbols.add(entry.getKey());
            }
        }
        int totalPages = (int) Math.ceil((double) symbols.size() / itemsPerPage);
        if (page < 0) page = 0;
        if (page >= totalPages && totalPages > 0) page = totalPages - 1;
        Collections.sort(symbols);

        currentPageSymbols.clear();
        int startIndex = page * itemsPerPage;
        for (int i = startIndex; i < startIndex + itemsPerPage && i < symbols.size(); i++) {
            String symbol = symbols.get(i);
            currentPageSymbols.add(symbol);
            addStockItem(i - startIndex, symbol);

        }

        if (page > 0) {
            addNavigationItem(45, Material.ARROW,
                    LangHelper.getString("gui.previous-page"),
                    Collections.singletonList(LangHelper.getString("gui.previous-page-hover")));
        }
        if (page < totalPages - 1) {
            addNavigationItem(53, Material.ARROW,
                    LangHelper.getString("gui.next-page"),
                    Collections.singletonList(LangHelper.getString("gui.next-page-hover")));
        }

        addNavigationItem(49, Material.BOOK,
                LangHelper.getString("gui.page-status", page+1, totalPages), null);
    }

    private void addStockItem(int slot, String symbol) {
        stockManager.loadStockIfNeeded(symbol);
        String name = stockManager.getStockName(symbol);
        double price = stockManager.getStockPrice(symbol);
        double changePercent = stockManager.getChangePercent(symbol);

        ChatColor color = changePercent >= 0 ? ChatColor.GREEN : ChatColor.RED;
        Material icon = changePercent >= 0 ? Material.EMERALD : Material.REDSTONE;

        ItemStack item = new ItemStack(icon);
        ItemMeta meta = item.getItemMeta();
        meta.setDisplayName(ChatColor.YELLOW + name);

        List<String> lore = new ArrayList<>();
        for (String line : LangHelper.getStringList("gui.item-lore")) {
            String formattedLine = line
                    .replace("%symbol%", symbol)
                    .replace("%price%", String.format("%.2f", price))
                    .replace("%sign%", changePercent >= 0 ? "+" : "")
                    .replace("%change%", String.format("%.2f", changePercent));
            lore.add(formattedLine);
        }

        for (int i = 0; i < lore.size(); i++) {
            lore.set(i, (i == lore.size() - 1 ? color : ChatColor.GRAY) + lore.get(i));
        }
        meta.setLore(lore);
        item.setItemMeta(meta);
        inventory.setItem(slot, item); // 直接设置新物品
        lore.add(ChatColor.GOLD + LangHelper.getString("gui.click-to-buy"));
    }
    private void addNavigationItem(int slot, Material material, String name, List<String> lore) {
        ItemStack item = new ItemStack(material);
        ItemMeta meta = item.getItemMeta();
        meta.setDisplayName(ChatColor.RED + name);
        if (lore != null) {
            meta.setLore(lore);
        }
        item.setItemMeta(meta);
        inventory.setItem(slot, item);
    }

    public void handleClick(int slot) {
        if (slot == 45 && currentPage > 0) {
            updatePage(currentPage - 1);
        } else if (slot == 53) {
            updatePage(currentPage + 1);
        }

        if (slot >= 0 && slot < itemsPerPage) {
            if (slot < currentPageSymbols.size()) {
                String symbol = currentPageSymbols.get(slot);
                openBuyQuantityGUI(symbol); // 直接打开购买界面
            }
        }
    }

    private void openBuyQuantityGUI(String symbol) {
        Inventory quantityGUI = Bukkit.createInventory(
                player,
                9,
                LangHelper.getString("gui.buy-title", symbol)
        );

        int[] quantities = {1, 5, 10, 20};
        for (int i = 0; i < quantities.length; i++) {
            ItemStack item = new ItemStack(Material.PAPER);
            ItemMeta meta = item.getItemMeta();
            meta.setDisplayName(ChatColor.YELLOW + "" + quantities[i] + " 股");
            item.setItemMeta(meta);
            quantityGUI.setItem(i, item);
        }

        player.openInventory(quantityGUI);
        plugin.getBuyManager().setPlayerSelection(player, symbol);
    }

    public void refreshCurrentPage() {
        updatePage(currentPage);
    }
}